package com.bank.serviceimpl;

import com.bank.dao.AccountDao;
import com.bank.dao.DetailDao;
import com.bank.daoimpl.AccountDaoImpl;
import com.bank.daoimpl.DetailDaoImpl;
import com.bank.javabean.Account;
import com.bank.javabean.Detail;
import com.bank.service.UserService;

import java.util.ArrayList;

/**
 * @Auther: Liu
 */
public class UserServiceImpl implements UserService {
    private AccountDao accountDao = new AccountDaoImpl();
    private DetailDao detailDao = new DetailDaoImpl();


    @Override
    public Account UserLogin(String username, String password) {
        ArrayList<Account> accounts = accountDao.selectByUsernameAndPassword(username, password);
        if (!accounts.isEmpty()) {
            return accounts.get(0);
        }
        return null;
    }

    @Override
    public void resetPassword(int id, String password) {
        accountDao.updatePasswordById(id, password);
    }

    @Override
    public Account findMyInfo(int id) {
        ArrayList<Account> accounts = accountDao.selectById(id);
        if (!accounts.isEmpty()) {
            return accounts.get(0);
        }
        return null;
    }

    @Override
    public void deposit(String username, double money) {
        accountDao.updateAddMoney(username, money);
        Detail detail = new Detail(username, username, money, 1);
        detailDao.insertDetail(detail);
    }

    @Override
    public void withdrawal(String username, double money) {
        ArrayList<Account> accounts = accountDao.selectByUsername(username);
        Account account = accounts.get(0);
        if (money <= account.getMoney()) {
            accountDao.updateSubMoney(username, money);
            Detail detail = new Detail(username, username, money, 2);
            detailDao.insertDetail(detail);
        }
    }

    @Override
    public void transferMoney(String uname, String tname, double money) {
        ArrayList<Account> accounts = accountDao.selectByUsername(uname);
        ArrayList<Account> accounts1 = accountDao.selectByUsername(tname);
        Account account = accounts.get(0);
        if (money <= account.getMoney() && !accounts1.isEmpty()) {
            accountDao.updateMoneyToUsername(uname, tname, money);
            Detail detail = new Detail(uname, tname, money, 3);
            detailDao.insertDetail(detail);
        }
    }

    @Override
    public ArrayList<Detail> findMyDetail(String username) {

        return detailDao.selectByUnameAndTname(username);
    }
}
